<?php
use think\Db;
/**
 * @param $data
 * @param $die
 */
function dd($data,$die = 1)
{
    echo "<pre>";print_r($data);
    if ($die==1) die;
}

/**
 * 转成标准数组
 * @param $data
 * @return mixed
 */
function toArray($data)
{
    $data = json_decode(json_encode($data),true);
    return $data;
}

/**
 * 检测推荐人
 * @param string $username
 * @return string
 * @throws \think\exception\DbException
 * @throws Exception
 */
function checkTjrInfo($username = '')
{
    //如果为空，则默认公司推荐人
    if (empty($username)) return 'company';
    $user = Db::name('user')->where(['username'=>$username,'status'=>'normal'])->field('id')->find();
    if(!$user) {
        throw new \think\Exception('该推荐人不存在');
    }
    return $username;
}


/**
 * 更新直推数和推荐团队人数
 * @param $tjr_username
 * @param $num
 * @param $team
 * @throws \think\Exception
 * @throws \think\exception\DbException
 */
function updateTeamNumber($tjr_username, $num, $team)
{
    $userModel = Db::name('user');
    //更新直推推荐
    if($num < 0) {
        $userModel->where(['username'=>$tjr_username])->setDec('tjr_num',abs($num));
    }else{
        $userModel->where(['username'=>$tjr_username])->setInc('tjr_num',$num);
    }
    //推荐上级团队总人数要更新
    $tjrInfo = $userModel->where(array('username'=>$tjr_username))->field('id,tjr_string')->find();
    if($tjrInfo){
        //包含直推上级
        $tjr_string = !empty($tjrInfo['tjr_string']) ? ($tjrInfo['tjr_string'].','.$tjrInfo['id']) : $tjrInfo['id'];
        $tjr_string = trim($tjr_string,',');
        if($team < 0){
            $userModel->where('id','in',$tjr_string)->setDec('tjr_down_num',abs($team));
        }else{
            $userModel->where('id','in',$tjr_string)->setInc('tjr_down_num',$team);
        }
    }
}

/**
 * 获取从min到max的网体会员
 * @param $username
 * @param $min
 * @param $max
 * @param $treeUser
 * @return mixed
 * @throws \think\exception\DbException
 */
function getTreeDownUser($username, $min, $max, $treeUser)
{
    $userModel = Db::name('user');
    if($max >= $min) {
        $data = $userModel->where('tjr_username','in',$username)
            ->field('id,username,nickname,status,createtime,tjr_username,tjr_num,ceng_num')
            ->order('id asc')
            ->select();
        $up_username = '';
        foreach($data as $val) {
            $up_username .= $val['username'].',';
            $treeUser[$val['username']] = $val;
        }
        $up_username = trim($up_username,',');
        if (!empty($up_username)){
            return getTreeDownUser($up_username,$min+1,$max,$treeUser);
        }
    }
    return $treeUser;
}


/**
 * @return bool
 */
function is_weixin()
{
    if(isset($_SERVER) && strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !==false) {
        return true;
    }  else {
        return false;
    }
}